package com.ruoyi.framework;

import com.ruoyi.framework.exception.UtilException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

/**
 * 若依环境配置加载器
 */
public class RuoYiDefaultConfigLoader implements EnvironmentPostProcessor, Ordered {

    private static final String RUO_YI_DEFAULT_SOURCES_NAME = "ruoyi-Default-PropertySources";
    private static final Properties PROPERTIES = new Properties();

    private static final Set<String> MUST_CONFIG_KEY_SET = new HashSet<>();

    static {
        MUST_CONFIG_KEY_SET.add("ruoyi.project.name");
        MUST_CONFIG_KEY_SET.add("ruoyi.project.version");
        MUST_CONFIG_KEY_SET.add("ruoyi.project.copyright-year");
        MUST_CONFIG_KEY_SET.add("ruoyi.project.profile");
        MUST_CONFIG_KEY_SET.add("ruoyi.project.logo-text");
        MUST_CONFIG_KEY_SET.add("ruoyi.project.website-title");
    }

    /**
     * 主要是为了获取主程序的配置参数
     */
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        // 判断必填配置是否有填
        for (String key : MUST_CONFIG_KEY_SET) {
            if (environment.containsProperty(key)) {
                continue;
            }
            throw new UtilException("missing.configuration: " + key);
        }

        // 获取默认配置
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        ClassPathResource resource = new ClassPathResource("ruoyi_default_config.yml");
        try {
            List<PropertySource<?>> propertySources = yamlPropertySourceLoader.load("ruoyi_default_config", resource);
            PropertySource<?> propertySource = propertySources.get(0);
            String[] propertyNames = ((OriginTrackedMapPropertySource) propertySource).getPropertyNames();
            for (String propertyName : propertyNames) {
                if (environment.containsProperty(propertyName)) {
                    continue;
                }
                PROPERTIES.put(propertyName, propertySource.getProperty(propertyName));
            }
            environment.getPropertySources().addLast(new PropertiesPropertySource(RUO_YI_DEFAULT_SOURCES_NAME, PROPERTIES));
        } catch (IOException exception) {
            throw new UtilException(exception);
        }
    }


    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
